package com.wjh.controller;

import com.wjh.bean.Constants;
import com.wjh.bean.Result;
import com.wjh.common.UrlCommon;
import com.wjh.feign.MemberServiceFeign;
import com.wjh.pojo.UserEntity;
import com.wjh.utils.CookiesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;

/**
 * @Author: 王金海
 * @Description:
 * @Date: Created by Administrator on 2018/6/13.
 * @Modified By:
 */
@Controller
@RequestMapping("/login")
public class LoginController extends UrlCommon{


    @Autowired
    MemberServiceFeign memberServiceFeign;
    @GetMapping
    public String login(){
        return LOGIN;
    }

    @PostMapping
    public String login(UserEntity userEntity, HttpServletRequest request, HttpServletResponse response){
        Result result = memberServiceFeign.login(userEntity);
        if (result.getCode()!= Constants.HTTP_RES_CODE_200) {
            request.setAttribute("error",result.getMsg());
            return LOGIN;
        }
        LinkedHashMap  data =(LinkedHashMap) result.getData();
        String token = (String)data.get("token");
        if (ObjectUtils.isEmpty(token)) {
            request.setAttribute("error","会话已失效");
            return LOGIN;
        }
        CookiesUtil.setCookie(response,Constants.MEMBER_TOKEN_COOKIE,token,Constants.MEMBER_TOKEN_COOKIE_TIME);
        return "redirect:/";
    }
}
